<!--
 * @author  dumeng
 * @desc  新建/编辑活动报名
-->
<template>
  <div class="hdbm-create">
    <div class="hdbm-create-title">新建/编辑活动报名</div>
    <section v-loading="loading" class="hdbm-create-main">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        class="form"
      >
        <el-form-item label="名称" prop="mainTitle">
          <el-input v-model="form.mainTitle" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="简介" prop="briefIntroduction">
          <el-input
            v-model="form.briefIntroduction"
            :rows="6"
            type="textarea"
            placeholder="请输入简介"
          />
        </el-form-item>
        <el-form-item label="引导图" prop="coverImgId" required>
          <image-upload
            :key="uploadFile.imagecropperKey"
            v-model="form.coverImgId"
            :preview-id="uploadFile.viewId"
            :forever="true"
            :width="316"
            :view="uploadFile.view"
            :height="213"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>

        <el-form-item label="活动时间" prop="param3">
          <el-input v-model="form.param3" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="报名起止时间" prop="time">
          <el-date-picker
            v-model="form.time"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            :style="{width:'100%'}"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-form-item>

        <el-form-item label="活动详情">
          <tinymce v-if="showtinymce" v-model="form.text" :height="300" />
        </el-form-item>
        <el-form-item label="附件">
          <div class="selectbtn" @click="filesAdd">添加附件</div>
          <draggable
            v-if="filesList.length"
            v-model="filesList"
            :animation="340"
            handle=".file-index-move"
          >
            <el-row
              v-for="(item, index) in filesList"
              :key="index"
              class="attachment-item"
            >
              <template v-if="item.attachmentId">
                <el-col :span="8">
                  <el-input v-model="item.attachmentName" @blur="isEmpty" />
                </el-col>
                <el-col :span="1" style="text-align: center">
                  <el-button
                    style="padding: 3px 0; font-size: 22px"
                    type="text"
                    icon="el-icon-close"
                    @click="filesDel(item, index)"
                  />
                </el-col>
                <el-col :span="1" style="text-align: center">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="拖动调整顺序"
                    placement="top"
                  >
                    <el-button
                      class="file-index-move"
                      style="padding: 3px 0; font-size: 22px"
                      type="text"
                      icon="el-icon-rank"
                    />
                  </el-tooltip>
                </el-col>
              </template>
            </el-row>
          </draggable>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input
            v-model.number="form.sort"
            placeholder="请输入排序号（值越大，越靠前）"
          />
        </el-form-item>
      </el-form>
    </section>
    <section class="hdbm-create-footer">
      <el-button
        style="padding: 10px 30px"
        @click="
          () => {
            $router.back();
          }
        "
      >取 消
      </el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
    <video-upload
      v-if="uploadFile.showUpload===1"
      ref="videoUpload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </video-upload>
    <image-no-cropper-upload
      v-if="uploadFile.showUpload===2"
      ref="imageUpload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </image-no-cropper-upload>
    <upload
      v-if="uploadFile.showUpload===3"
      ref="upload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </upload>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :visible.sync="preview.state"
      title="预览"
      center
      width="600px"
    >
      <preview :file-id="preview.fileId" />
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :visible.sync="imageaddState"
      title="图片上传"
      center
      width="600px"
    >
      <div class="image-upload-dialog">
        <el-form label-width="80px">
          <el-form-item label="图片">
            <img
              v-if="imageadd.attachmentId"
              class="upload-img"
              :src="uploadFile.view + imageadd.attachmentId"
            >
            <div v-else class="icon-wrap" @click="handleFileUpload('image')">
              <i class="el-icon-plus avatar-uploader-icon" />
            </div>
          </el-form-item>
          <el-form-item label="简介">
            <el-input
              v-model="imageadd.explain"
              placeholder="请输入内容"
              maxlength="100"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          type="primary"
          @click="imageaddState = false"
        >取消</el-button>
        <el-button
          style="padding: 8px 30px"
          type="primary"
          @click="submitUploadImage()"
        >确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import Upload from '@/components/upload'
import Preview from '../components/VideoPreview'
import draggable from 'vuedraggable'
import {
  insert,
  update,
  get
} from '../api'
import Tinymce from '@/components/Tinymce'
import elDragDialog from '@/directive/el-drag-dialog'
import VideoUpload from '@/components/VideoUpload'
import ImageNoCropperUpload from '@/components/ImageNoCropperUpload' // base on element-ui
export default {
  name: 'Hdbmmanage',
  components: { ImageUpload, VideoUpload, Upload, ImageNoCropperUpload, Tinymce, Preview, draggable },
  directives: { elDragDialog },
  filters: {
    filterTip(ft) {
      if (ft === 'image') {
        return '只能上传：图片文件'
      } else if (ft === 'video') {
        return '只能上传：视频文件'
      } else {
        return '请上传附件'
      }
    }
  },
  data() {
    return {
      showtinymce: false,
      loading: false,
      form: {
        id: '',
        mainTitle: '',
        withTitle: '',
        briefIntroduction: '',
        coverImgId: '',
        source: '',
        text: '',
        sort: '',
        publisher: '',
        publishTime: '',
        param1: '',
        param2: '',
        param3: '',
        time: '',
        param6: ''
      },
      rules: {
        mainTitle: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        briefIntroduction: [
          { required: true, message: '请输入简介', trigger: 'blur' },
          { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
        ],
        coverImgId: [
          { required: true, message: '请上传引导图', trigger: 'change' }
        ],
        param3: [
          { required: true, message: '请输入活动时间', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '请选择活动起止时间', trigger: 'change' }
        ]
      },
      imagesList: [],
      videosList: [],
      filesList: [],
      imageaddState: false,
      imageadd: {
        attachmentId: '',
        explain: '',
        attachmentName: ''
      },
      state: 'create',
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: -1, // 1视频 2图片 3附件
        accept: '',
        fileType: '',
        fileIndex: 0
      },
      preview: {
        state: false,
        fileId: ''
      }
    }
  },
  created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      } else {
        this.getData(this.$route.query.i)
      }
    } else {
      this.showtinymce = true
    }
  },
  methods: {
    CleanPastedHTML(input) {
      if (!input) {
        return ''
      }
      input = input.replace(/<\/?[^>]*>/g, '') // 去除HTML tag
      input = input.replace(/(\r)/ig, '')
      input = input.replace(/(\n)/ig, '')
      input = input.replace(/(\t)/ig, '')
      input = input.replace(/ /ig, '')// 去掉
      return input.replace(/&(.*?);/ig, '')
    },
    isEmpty(e) {
      if (e.target.value === '') {
        this.$message({
          message: '附件名称不能为空！',
          type: 'warning'
        })
      }
    },
    handleFileUpload(fileType, i) {
      this.uploadFile.fileType = fileType
      this.uploadFile.fileIndex = i
      if (fileType === 'video') {
        this.uploadFile.accept = 'video/mp4'
        this.uploadFile.showUpload = 1
      } else if (fileType === 'image') {
        this.uploadFile.accept = 'image/*'
        this.uploadFile.showUpload = 2
      } else {
        this.uploadFile.accept = ''
        this.uploadFile.showUpload = 3
      }
    },
    /**
     * 新闻图片-继续添加
     */
    imagesAdd() {
      for (const i in this.imageadd) {
        this.imageadd[i] = ''
      }
      this.imageaddState = true
    },
    submitUploadImage() {
      const obj = Object.assign({}, this.imageadd)
      this.imagesList.push(obj)
      this.imageaddState = false
    },
    /**
     * 新闻视频-继续添加
     */
    videosAdd() {
      if (this.videosList.length === 0 || this.videosList[this.videosList.length - 1].attachmentId !== '') {
        const temp = {
          attachmentId: '',
          explain: '',
          attachmentName: ''
        }
        this.videosList.push(temp)
      }
      this.handleFileUpload('video', this.videosList.length - 1)
    },
    /**
     * 附件-继续添加
     */
    filesAdd() {
      const temp = {
        attachmentId: '',
        explain: '',
        attachmentName: '',
        attachmentNameOld: ''
      }
      this.filesList.push(temp)
      this.handleFileUpload('file', this.filesList.length - 1)
    },
    /**
     * 新闻图片-删除
     */
    imagesDel(item, index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.imagesList.splice(index, 1)
      }).catch()
    },
    /**
     * 新闻视频-删除
     */
    videosDel(item, index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.videosList.splice(index, 1)
      }).catch()
    },
    /**
     * 附件-删除
     */
    filesDel(item, index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.filesList.splice(index, 1)
      }).catch()
    },
    uploadSuccess(id, files) {
      if (id) {
        const fileType = this.uploadFile.fileType
        const fileIndex = this.uploadFile.fileIndex
        if (fileType === 'image') {
          this.imageadd.attachmentId = id
          this.imageadd.attachmentName = files[0].name
        } else if (fileType === 'video') {
          this.videosList[fileIndex].attachmentId = id
          this.videosList[fileIndex].attachmentName = files[0].name
        } else {
          this.filesList[fileIndex].attachmentId = id
          this.filesList[fileIndex].attachmentName = files[0].name
          this.filesList[fileIndex].attachmentNameOld = files[0].name
        }
      }
      this.uploadFile.showUpload = -1
    },
    /**
     * 视频预览
     */
    handlePreview(id) {
      this.preview.fileId = id
      this.preview.state = true
    },
    /**
     * 新闻图片-删除
     */
    // eslint-disable-next-line no-dupe-keys
    filesDel(item, index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.filesList.splice(index, 1)
      }).catch()
    },
    onSubmint() {
      if (this.filesList.filter(item => {
        return item.attachmentId
      }).filter(ite => {
        return ite.attachmentName === ''
      }).length > 0) {
        this.$message({
          message: '请填写附件名称！',
          type: 'warning'
        })
        return
      }
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['param4'] = params.time && params.time.length > 0 ? params.time[0] : ''
            params['param5'] = params.time && params.time.length > 0 ? params.time[1] : ''
            delete params['time']
            if (this.form.briefIntroduction === '') {
              const text = this.CleanPastedHTML(this.form.text)
              params['briefIntroduction'] = text.length > 200 ? text.substring(0, 200) : text.substring(0, text.length - 1)
            }
            params['picJson'] = this.imagesList.filter(item => {
              return item.attachmentId
            }).length > 0 ? JSON.stringify(this.imagesList.filter(item => {
                return item.attachmentId
              })) : ''
            params['videoJson'] = this.videosList.filter(item => {
              return item.attachmentId && item.attachmentName
            }).length > 0 ? JSON.stringify(this.videosList.filter(item => {
                return item.attachmentId && item.attachmentName
              })) : ''
            params['fileJson'] = this.filesList.filter(item => {
              return item.attachmentId
            }).length > 0 ? JSON.stringify(this.filesList.filter(item => {
                return item.attachmentId
              })) : ''
            return new Promise((resolve, reject) => {
              insert(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.back()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })

            const params = Object.assign({}, this.form)
            params['param4'] = params.time && params.time.length > 0 ? params.time[0] : ''
            params['param5'] = params.time && params.time.length > 0 ? params.time[1] : ''
            delete params['time']
            if (this.form.briefIntroduction === '') {
              const text = this.CleanPastedHTML(this.form.text)
              params['briefIntroduction'] = text.length > 200 ? text.substring(0, 200) : text.substring(0, text.length - 1)
            }
            params['picJson'] = this.imagesList.filter(item => {
              return item.attachmentId
            }).length > 0 ? JSON.stringify(this.imagesList.filter(item => {
                return item.attachmentId
              })) : ''
            params['videoJson'] = this.videosList.filter(item => {
              return item.attachmentId && item.attachmentName
            }).length > 0 ? JSON.stringify(this.videosList.filter(item => {
                return item.attachmentId && item.attachmentName
              })) : ''
            params['fileJson'] = this.filesList.filter(item => {
              return item.attachmentId
            }).length > 0 ? JSON.stringify(this.filesList.filter(item => {
                return item.attachmentId
              })) : ''
            return new Promise((resolve, reject) => {
              update(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.back()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if (key === 'time') {
              if (data['param4'] && data['param5']) {
                this.form[key] = [data['param4'], data['param5']]
              }
            } else {
              this.form[key] = data[key]
            }
          }
          this.uploadFile.viewId = data.coverImgId
          this.imagesList = data.picList || []
          this.videosList = data.videoList || []
          this.filesList = data.fileList || []
          this.showtinymce = true
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

.hdbm-create {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .hdbm-create-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: "";
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .hdbm-create-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }

    .hdbm-image {
      .el-card__header {
        padding-top: 8px;
        padding-bottom: 8px;
      }
    }

    .images-item {
      position: relative;
      margin-bottom: 10px;

      .upload-img {
        width: 100%;
        height: 160px;
        display: block;
      }

      .el-input {
        display: block;
      }

      .custom-uploader {
        width: 100%;
        display: block;

        .icon-wrap {
          width: 100%;
          height: 160px;
        }
      }

      .el-button {
        position: absolute;
        right: 10px;
        top: 0;
        color: #fff;

        i {
          background: rgba(0, 0, 0, 0.4);
          border-radius: 50%;
          padding: 2px;
        }

        &.image-index-move {
          right: 40px;
        }
      }
    }

    .images-add {
      color: $mainColor;
      font-size: 14px;
      padding-left: 80px;
      cursor: pointer;
      margin-bottom: 20px;
    }

    .upload-img {
      width: 100%;
      height: 160px;
    }

    .attachment-item {
      margin-bottom: 10px;

      .item-btn {
        font-size: 20px;
        cursor: pointer;
      }

      .video-item {
        position: relative;
        cursor: pointer;

        .el-button {
          position: absolute;
          right: 10px;
          top: 0;
          color: #fff;

          i {
            background: rgba(0, 0, 0, 0.4);
            border-radius: 50%;
            padding: 2px;
          }

          &.video-index-move {
            right: 40px;
          }
        }
      }
    }
  }

  .hdbm-create-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }

  .image-upload-dialog {
    .icon-wrap {
      width: 300px;
      height: 160px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(247, 247, 248, 1);
      border: 1px solid rgba(226, 227, 232, 1);
      border-radius: 4px;

      .avatar-uploader-icon {
        font-size: 48px;
        color: #dadada;
        width: 300px;
        text-align: center;
      }
    }

    .upload-img {
      display: block;
      width: 300px;
      height: 160px;
      border-radius: 4px;
    }
  }
}
</style>
<style lang="scss">

.hdbm-create {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;

    .classify-tree-con-scrollbar {
      overflow: hidden;

      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;

      .tree-node-txt {
        flex: 1;
      }
    }
  }

  .el-tag--medium {
    line-height: 32px;
    height: 32px;

    & + .el-tag--medium {
      margin-left: 10px;
    }
  }
}
</style>
